// pages/index/carNotice/carNotice.js
const app = getApp()
const request = require('../../../utils/request')
const utils = require('../../../utils/util')

Page({
  data: {
    page: 1,
    newsList: [],
    total: 0,
  },

  onLoad() {
    this.getNewsList()
  },

  onPullDownRefresh: utils.throttle(function () {
    this.setData({
      page: 1,
      newsList: []
    })
    this.getNewsList()
  }, 1000),

  onReachBottom: utils.throttle(function () {
    if (this.data.page <= this.data.total) {
      this.getNewsList()
    } else {
      wx.showToast({
        icon: 'none',
        title: '没有更多资讯了'
      })
    }
  }, 1000),

  getNewsList() {
    wx.showLoading()

    request.get('news_list', this.data.page)
      .then(res => {
        wx.hideLoading()
        if (res.data && res.data.length) {
          res.data = res.data.map(v => {
            v.cover = utils.repalceBacklash(v.cover)
            return v
          })
          
          this.setData({
            newsList: [...res.data, ...this.data.newsList],
            total: res.pagenum,
            page: this.data.page + 1
          })
        }
      })
      .catch(error => {
        wx.showToast({
          icon: 'none',
          title: error.msg && error.msg
        })
      })
      .finally(_ => {
        // wx.hideLoading()
      })
  },

  toDetail(e) {
    wx.navigateTo({
      url: `/pages/index/carNotice/carNoticeDetail/carNoticeDetail?id=${e.currentTarget.dataset.id}`
    })
  }
})